import React, { useEffect, useRef } from 'react';
import * as d3 from 'd3';
import { Bookmark, GraphData, GraphNode, GraphLink } from '../../types';

interface NetworkGraphProps {
  bookmarks: Bookmark[];
}

const NetworkGraph: React.FC<NetworkGraphProps> = ({ bookmarks }) => {
  const svgRef = useRef<SVGSVGElement>(null);

  useEffect(() => {
    if (!bookmarks.length || !svgRef.current) return;

    // 转换书签为网络图谱数据
    const graphData = transformBookmarksToGraphData(bookmarks);
    renderGraph(graphData);
  }, [bookmarks]);

  // 将书签转换为力导向图数据格式
  const transformBookmarksToGraphData = (bookmarks: Bookmark[]): GraphData => {
    const nodes: GraphNode[] = [];
    const links: GraphLink[] = [];
    const bookmarkMap = new Map<string, GraphNode>();

    // 创建中心节点 - 代表用户
    const centerNode: GraphNode = {
      id: 'center',
      title: '我的书签',
      url: '',
      group: 0,
    };
    nodes.push(centerNode);

    // 为每个书签创建节点
    bookmarks.forEach((bookmark) => {
      const primaryCategory = bookmark.categories[0] || { id: 'other', name: '其他' };
      const groupIndex = ['tech', 'design', 'entertainment', 'news', 'other'].indexOf(primaryCategory.id) + 1;

      const node: GraphNode = {
        id: bookmark.id,
        title: bookmark.title,
        url: bookmark.url,
        group: groupIndex > 0 ? groupIndex : 5, // 默认为其他分类
      };

      nodes.push(node);
      bookmarkMap.set(bookmark.id, node);

      // 连接到中心节点
      links.push({
        source: 'center',
        target: bookmark.id,
        value: 1,
      });

      // 同一类别的书签相互连接（适度连接，避免图过于密集）
      if (Math.random() < 0.3) { // 只连接30%的同类书签
        bookmarks
          .filter(
            (b) =>
              b.id !== bookmark.id &&
              b.categories.some((c) => bookmark.categories.some((bc) => bc.id === c.id))
          )
          .slice(0, 2) // 最多连接2个同类书签
          .forEach((relatedBookmark) => {
            links.push({
              source: bookmark.id,
              target: relatedBookmark.id,
              value: 0.5, // 较弱的连接
            });
          });
      }
    });

    return { nodes, links };
  };

  // 渲染力导向图
  const renderGraph = (data: GraphData) => {
    const svg = d3.select(svgRef.current);
    const width = svgRef.current?.clientWidth || 800;
    const height = svgRef.current?.clientHeight || 600;

    // 清除之前的图形
    svg.selectAll('*').remove();

    // 定义颜色比例尺
    const color = d3.scaleOrdinal(d3.schemeCategory10);

    // 创建力模拟
    const simulation = d3
      .forceSimulation(data.nodes as any)
      .force(
        'link',
        d3
          .forceLink(data.links)
          .id((d: any) => d.id)
          .distance(70)
      )
      .force('charge', d3.forceManyBody().strength(-200))
      .force('center', d3.forceCenter(width / 2, height / 2))
      .force('collision', d3.forceCollide().radius(30));

    // 创建连线
    const link = svg
      .append('g')
      .attr('stroke', '#999')
      .attr('stroke-opacity', 0.6)
      .selectAll('line')
      .data(data.links)
      .join('line')
      .attr('stroke-width', (d: any) => Math.sqrt(d.value));

    // 创建节点
    const node = svg
      .append('g')
      .selectAll('.node')
      .data(data.nodes)
      .join('g')
      .attr('class', 'node')
      .call(
        d3
          .drag<SVGGElement, GraphNode>()
          .on('start', dragstarted)
          .on('drag', dragged)
          .on('end', dragended) as any
      );

    // 为节点添加圆形背景
    node
      .append('circle')
      .attr('r', (d: any) => (d.id === 'center' ? 15 : 8))
      .attr('fill', (d: any) => color(String(d.group)))
      .attr('stroke', '#fff')
      .attr('stroke-width', 1.5);

    // 为节点添加标题
    node
      .append('text')
      .attr('dx', 12)
      .attr('dy', '.35em')
      .text((d: any) => (d.id === 'center' ? '我的书签' : d.title.substring(0, 15) + (d.title.length > 15 ? '...' : '')))
      .attr('font-size', (d: any) => (d.id === 'center' ? '14px' : '10px'))
      .style('pointer-events', 'none');

    // 添加节点点击事件
    node.on('click', (event: any, d: any) => {
      if (d.id !== 'center' && d.url) {
        chrome.tabs.create({ url: d.url });
      }
    });

    // 添加标题提示
    node.append('title').text((d: any) => d.title);

    // 更新力模拟
    simulation.on('tick', () => {
      link
        .attr('x1', (d: any) => d.source.x)
        .attr('y1', (d: any) => d.source.y)
        .attr('x2', (d: any) => d.target.x)
        .attr('y2', (d: any) => d.target.y);

      node.attr('transform', (d: any) => `translate(${d.x},${d.y})`);
    });

    // 拖拽事件处理函数
    function dragstarted(event: d3.D3DragEvent<SVGGElement, GraphNode, any>, d: any) {
      if (!event.active) simulation.alphaTarget(0.3).restart();
      d.fx = d.x;
      d.fy = d.y;
    }

    function dragged(event: d3.D3DragEvent<SVGGElement, GraphNode, any>, d: any) {
      d.fx = event.x;
      d.fy = event.y;
    }

    function dragended(event: d3.D3DragEvent<SVGGElement, GraphNode, any>, d: any) {
      if (!event.active) simulation.alphaTarget(0);
      d.fx = null;
      d.fy = null;
    }
  };

  return (
    <div className="h-[500px] w-full bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden">
      <svg ref={svgRef} width="100%" height="100%" />
    </div>
  );
};

export default NetworkGraph; 